package com.jacky.demo.dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by Administrator on 2017-12-21.
 */

public class WebPopupMenu {

    public static void show(final Context context, final String imgUrl) {
        if(TextUtils.isEmpty(imgUrl)) return;

        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setItems(new String[]{"保存图片"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                File file = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                        "ly" + System.currentTimeMillis() + ".jpg");
                if(imgUrl.startsWith("http")) {
                    downFile(imgUrl, file, new Runnable() {
                        @Override
                        public void run() {
                            showToast(context, "图片保存在下载目录");
                        }
                    }, new Runnable() {
                        @Override
                        public void run() {
                            showToast(context, "图片保存失败");
                        }
                    });
                } else if(imgUrl.startsWith("data")) {
                    byte[] bytes = android.util.Base64.decode(imgUrl.split(",")[1], android.util.Base64.DEFAULT);
                    if(save(bytes, file)) {
                        showToast(context, "图片保存在下载目录");
                    } else {
                        showToast(context, "图片保存失败");
                    }
                }
            }
        });
        dialog.show();
    }

    private static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    public static void downFile(String url, final File file, final Runnable success, final Runnable failure) {
        //TODO... 自己去实现下载功能
//        Request request = new Request.Builder().url(url).get().build();
//        mClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                runOnUiThread(failure);
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                try {
//                    saveFile(response.body(), file);
//                    runOnUiThread(success);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    runOnUiThread(failure);
//                }
//            }
//
//            private void saveFile(okhttp3.ResponseBody body,File destFile) throws Exception {
//                InputStream inputStream = null;
//                OutputStream outputStream = null;
//                try {
//                    inputStream = body.byteStream();
//                    outputStream = new FileOutputStream(destFile);
//                    byte[] fileReader = new byte[1024 * 2];
//
//                    while (true) {
//                        int read = inputStream.read(fileReader);
//                        if (read == -1) break;
//
//                        outputStream.write(fileReader, 0, read);
//                    }
//                    outputStream.flush();
//                }catch (Exception e) {
//                    throw e;
//                } finally {
//                    FileManager.close(inputStream);
//                    FileManager.close(outputStream);
//                }
//            }
//        });
    }

    public static boolean save(byte[] bytes, File file) {
        OutputStream stream = null;
        try {
            stream = new FileOutputStream(file);
            stream.write(bytes);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(stream);
        }
        return false;
    }

    public static void close(Closeable closeable) {
        if(closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
